package web

import (
	"bytes"
	"gitee.com/crack007/goose/gslog"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
)

var RequestLogMiddleware = &requestLogMiddleware{}

// 日志输出请求 body 参数。
type requestLogMiddleware struct {
}

func (x *requestLogMiddleware) Apply(iRoutes gin.IRoutes) {
	iRoutes.Use(x.Handle)
}

func (x *requestLogMiddleware) Handle(ctx *gin.Context) {
	// 读取请求 Body
	if ctx.Request.Method == http.MethodGet {
		ctx.Next()
		return
	}

	body, err := io.ReadAll(ctx.Request.Body)
	if err != nil {
		gslog.Error("Failed to read request body:", err)
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	// 将 Body 写回，以便后续处理函数可以读取
	ctx.Request.Body = io.NopCloser(bytes.NewBuffer(body))

	// 打印请求 Body 日志
	gslog.Info("%s [request]: %s", ctx.Request.URL.Path, string(body))
	ctx.Next()
}
